package com.spy.dish.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spy.common.constant.HttpStatus;
import com.spy.common.core.page.TableDataInfo;
import com.spy.oss.AliyunOSSOperator;
import com.spy.common.exception.base.BaseException;
import com.spy.common.utils.DateUtils;
import com.spy.dish.domain.DishIngredient;
import com.spy.dish.domain.DishStep;
import com.spy.dish.dto.DishDTO;
import com.spy.dish.dto.DishQueryDTO;
import com.spy.dish.mapper.DishIngredientMapper;
import com.spy.dish.mapper.DishStepMapper;
import com.spy.dish.vo.DishDetailVO;
import com.spy.dish.vo.DishVO;
import com.spy.system.domain.DishCategory;
import com.spy.system.mapper.DishCategoryMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spy.dish.mapper.DishMapper;
import com.spy.dish.domain.Dish;
import com.spy.dish.service.IDishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 菜品信息Service业务层处理
 *
 * @author zhaoxy
 * @date 2025-11-10
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishStepMapper dishStepMapper;

    @Autowired
    private DishIngredientMapper dishIngredientMapper;

    @Autowired
    private DishCategoryMapper dishCategoryMapper;
    /**
     * 查询菜品信息
     *
     * @param id 菜品信息主键
     * @return 菜品信息
     */
    @Override
    public Dish selectDishById(Long id) {
        return getById(id);
    }

    /**
     * 查询菜品信息列表
     *
     * @param dishQueryDTO 菜品信息
     * @return 菜品信息
     */
    @Override
    public TableDataInfo<DishVO>  selectDishList(DishQueryDTO dishQueryDTO) {
        Page<Dish> page = new Page<>(dishQueryDTO.getPageNum(), dishQueryDTO.getPageSize());
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        if (dishQueryDTO.getDishName() != null){
            wrapper.like(Dish::getDishName, dishQueryDTO.getDishName());
        }
        if (dishQueryDTO.getSpiceLevel()!= null){
            wrapper.eq(Dish::getSpiceLevel, dishQueryDTO.getSpiceLevel());
        }
        if (dishQueryDTO.getIsEnabled() != null){
            wrapper.eq(Dish::getIsEnabled, dishQueryDTO.getIsEnabled());
        }
        if (dishQueryDTO.getDishCategoryId() != null){
            wrapper.eq(Dish::getDishCategoryId, dishQueryDTO.getDishCategoryId());
        }
        Page<Dish> dishPage = page(page, wrapper);
        List<Dish> dishList = dishPage.getRecords();
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish dish : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            DishCategory dishCategory = dishCategoryMapper.selectDishCategoryById(dish.getDishCategoryId());
            dishVO.setDishCategoryName(dishCategory != null ? dishCategory.getName() : "未知分类");
            dishVOList.add(dishVO);
         }
        TableDataInfo<DishVO> dataInfo = new TableDataInfo<>();
        dataInfo.setCode(HttpStatus.SUCCESS);
        dataInfo.setMsg("查询成功");
        dataInfo.setRows(dishVOList);
        dataInfo.setTotal(dishPage.getTotal());

        return dataInfo;
    }

    /**
     * 新增菜品信息
     *
     * @param dish 菜品信息
     * @return 结果
     */
    @Override
    public int insertDish(Dish dish) {
        dish.setCreateTime(DateUtils.getNowDate());
        return save(dish) ? 1 : 0;
    }

    /**
     * 修改菜品信息
     *
     * @param dish 菜品信息
     * @return 结果
     */
    @Override
    public int updateDish(Dish dish) {
        dish.setUpdateTime(DateUtils.getNowDate());
        return updateById(dish) ? 1 : 0;
    }

    /**
     * 批量删除菜品信息
     *
     * @param ids 需要删除的菜品信息主键
     * @return 结果
     */
    @Override
    public int deleteDishByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除菜品信息信息
     *
     * @param id 菜品信息主键
     * @return 结果
     */
    @Override
    public int deleteDishById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 获取菜品信息详细信息，包括原料和步骤信息
     *
     * @param id
     * @return
     */
    @Override
    public DishDetailVO selectDishDetailById(Long id) {
        DishDetailVO dishDetailVO = new DishDetailVO();
        //1.获取菜品信息
        Dish dish = dishMapper.selectDishById(id);
        if (dish == null) {
            throw new BaseException("菜品不存在，ID：" + id);
        }
        BeanUtils.copyProperties(dish, dishDetailVO);
        Long dishCategoryId = dish.getDishCategoryId();
        // 调用分类Mapper查询分类信息（需注入dishCategoryMapper）
        DishCategory category = dishCategoryMapper.selectById(dishCategoryId);
        if (category != null) {
            // 将分类名称设置到VO中（假设dishDetailVO有setDishCategoryName方法）
            dishDetailVO.setDishCategoryName(category.getName());
        } else {
            // 可选：分类不存在时的处理（如设为默认值或抛异常）
            dishDetailVO.setDishCategoryName("未知分类");
        }
        //2.获取菜品原料信息
        LambdaQueryWrapper<DishIngredient> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishIngredient::getDishId, id);
        List<DishIngredient> dishIngredients = dishIngredientMapper.selectList(wrapper);
        dishDetailVO.setIngredients(dishIngredients);

        //3.获取菜品步骤信息
        LambdaQueryWrapper<DishStep> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DishStep::getDishId, id);
        List<DishStep> dishSteps = dishStepMapper.selectList(wrapper1);
        dishDetailVO.setSteps(dishSteps);

        return dishDetailVO;

    }

    /***
     * 新增菜品详细信息
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveDishDetail(DishDTO dishDTO) {
        //1.存储菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        save(dish);
        //2.存储ingredient信息
        List<DishIngredient> ingredients = dishDTO.getIngredients();
        if (ingredients != null && ingredients.size() > 0) {
            for (DishIngredient ingredient : ingredients) {
                ingredient.setDishId(dish.getId());
                dishIngredientMapper.insertDishIngredient(ingredient);
            }
        }
        //3.存储step信息
        List<DishStep> steps = dishDTO.getSteps();
        if (steps != null && steps.size() > 0) {
            for (DishStep step : steps) {
                step.setDishId(dish.getId());
                dishStepMapper.insertDishStep(step);
            }
        }
    }

    /**
     * 修改菜品信息
     *
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional
    public boolean updateDishDetail(DishDTO dishDTO) {
        try {
            //1.更新菜品信息
            Dish dish = new Dish();
            BeanUtils.copyProperties(dishDTO, dish);
            dishMapper.updateById(dish);
            //获取dishId
            Long id = dish.getId();
            //2.删除菜品的原料信息，然后新增
            LambdaQueryWrapper<DishIngredient> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DishIngredient::getDishId, id);
            dishIngredientMapper.delete(wrapper1);
            List<DishIngredient> ingredients = dishDTO.getIngredients();
            if (ingredients != null && ingredients.size() > 0) {
                for (DishIngredient ingredient : ingredients) {
                    ingredient.setDishId(id);
                    dishIngredientMapper.insertDishIngredient(ingredient);
                }
            }
            //3.删除菜品的步骤信息，然后新增
            LambdaQueryWrapper<DishStep> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(DishStep::getDishId, id);
            dishStepMapper.delete(wrapper2);

            List<DishStep> steps = dishDTO.getSteps();
            if (steps != null && steps.size() > 0) {
                for (DishStep step : steps) {
                    step.setDishId(id);
                    dishStepMapper.insertDishStep(step);
                }
            }
            //4.返回结果
            return true;
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除菜品详细信息
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int deleteDishDetailByIds(Long[] ids) {
        //1.批量删除菜品信息
        LambdaQueryWrapper<Dish> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(Dish::getId, ids);
        int delete = dishMapper.delete(wrapper1);
        //2.批量删除菜品的原料信息
        LambdaQueryWrapper<DishIngredient> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.in(DishIngredient::getDishId, ids);
        delete += dishIngredientMapper.delete(wrapper2);

        //3.批量删除菜品的步骤信息
        LambdaQueryWrapper<DishStep> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.in(DishStep::getDishId, ids);
        delete += dishStepMapper.delete(wrapper3);

        //4.返回结果
        return delete;
    }
}
